<template>
  <div class="container mx-auto p-4 bg-gray-50 min-h-screen">
    <h2 class="text-xl font-bold text-gray-800 mb-4">支付数据分析仪表盘</h2>
    <!-- 最近支付订单列表 -->
    <el-card class="page-container">
      <h1 class="text-3xl font-bold text-center mb-8 text-gray-800">最近支付订单</h1>
      <el-table :data="paymentPageListDate" style="width: 100%">
        <el-table-column label="订单ID" prop="orderId"></el-table-column>
        <el-table-column label="支付流水号" prop="paymentNo"></el-table-column>
        <el-table-column label="支付方式">
          <template #default="scope">
            <el-tag :type="scope.row.paymentType === 1 ? 'success' : 'primary'">
              {{ formatPaymentType(scope.row.paymentType) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="支付金额">
          <template #default="scope">
            <span :style="getAmountStyle(scope.row.amount)">{{ scope.row.amount | currency }}</span>
          </template>
        </el-table-column>
        <el-table-column label="支付时间" prop="paymentTimeStr"></el-table-column>
        <el-table-column label="退款时间" prop="refundTimeStr"></el-table-column>
        <el-table-column label="支付状态">
          <template #default="scope">
            <el-tag :type="getStatusType(scope.row.status)">
              {{ formatstatus(scope.row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <template #empty>
          <el-empty description="没有数据"/>
        </template>
      </el-table>
      <!-- 分页条 -->
      <el-pagination
          v-model:current-page="pageNum"
          v-model:page-size="pageSize"
          :page-sizes="[5 ,10, 15]"
          layout="jumper, total, sizes, prev, pager, next"
          background
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          style="margin-top: 20px; justify-content: flex-end"
      />
    </el-card>
    <!-- 年和月输入框 -->
    <div class="date-filter mb-6">
      <el-input
          v-model="formData.year"
          placeholder="请输入年份"
          type="number"
          style="width: 150px; margin-right: 30px;"
      ></el-input>
      <el-button type="primary" @click="handleDateQuery">查询</el-button>
      <el-button @click="resetDateFilter" style="margin-left: 10px;">重置</el-button>
    </div>
    <!-- 数据卡片 -->
    <el-card class="page-container">
      <div class="card-grid">
        <div class="data-card">
          <p class="text-gray-500 text-sm">总交易额</p>
          <p class="text-2xl font-bold text-gray-800">{{ totalAmount | currency }}</p>
          <p :class="amountGrowthRate >= 0 ? 'text-green-500' : 'text-red-500' + ' text-sm mt-2'">
            <i :class="amountGrowthRate >= 0 ? 'fa fa-arrow-up' : 'fa fa-arrow-down'"></i>
            {{ (amountGrowthRate) }}%
            <span class="text-gray-500">vs {{ comparePeriod }}</span>
          </p>
        </div>
        <div class="data-card">
          <p class="text-gray-500 text-sm">支付订单数</p>
          <p class="text-2xl font-bold text-gray-800">{{ totalOrder }}</p>
          <p :class="orderGrowthRate >= 0 ? 'text-green-500' : 'text-red-500' + ' text-sm mt-2'">
            <i :class="orderGrowthRate >= 0 ? 'fa fa-arrow-up' : 'fa fa-arrow-down'"></i>
            {{ (orderGrowthRate) }}%
            <span class="text-gray-500">vs {{ comparePeriod }}</span>
          </p>
        </div>
        <div class="data-card">
          <p class="text-gray-500 text-sm">退款率</p>
          <p class="text-2xl font-bold text-gray-800">{{ totalRefund }}%</p>
          <p :class="refundGrowthRate >= 0 ? 'text-red-500' : 'text-green-500' + ' text-sm mt-2'">
            <i :class="refundGrowthRate >= 0 ? 'fa fa-arrow-up' : 'fa fa-arrow-down'"></i>
            {{ (refundGrowthRate) }}%
            <span class="text-gray-500">vs {{ comparePeriod }}</span>
          </p>
        </div>
      </div>
    </el-card>
    <!-- 图表区域 -->
    <el-card class="page-container chart-container">
      <div class="chart-row">
        <!-- 支付方式分布 -->
        <div class="chart-item">
          <h2 class="text-xl font-bold text-gray-800 mb-4">支付方式分布</h2>
          <div class="chart-wrapper">
            <canvas id="paymentMethodChart"></canvas>
          </div>
        </div>
        <!-- 支付状态统计 -->
        <div class="chart-item">
          <h2 class="text-xl font-bold text-gray-800 mb-4">支付状态统计</h2>
          <div class="chart-wrapper">
            <canvas id="paymentStatusChart"></canvas>
          </div>
        </div>
      </div>
    </el-card>
    <!-- 交易趋势 -->
    <div class="bg-white rounded-lg shadow p-6 lg:col-span-2">
      <h2 class="text-xl font-bold text-gray-800 mb-4">{{ trendTitle }}</h2>
      <div class="h-80">
        <canvas id="transactionTrendChart"></canvas>
      </div>
    </div>
    <!-- 金额分布 -->
    <div class="bg-white rounded-lg shadow p-6">
      <h2 class="text-xl font-bold text-gray-800 mb-4">支付金额分布</h2>
      <div class="h-80">
        <canvas id="amountDistributionChart"></canvas>
      </div>
    </div>
  </div>
</template>
<script>
import { ref, onMounted, watch } from 'vue';
import Chart from 'chart.js/auto';
import { paymentList, paymentMonthList, paymentPageList, paymentYearList } from "@/api/payment";
import { useUserInfoStore } from "@/stores/userInfo";
// import dayjs from 'dayjs';
import { Delete, Edit } from "@element-plus/icons-vue";
import {ElMessage} from "element-plus";
export default {
  name: 'PaymentDashboard',
  computed: {
    Delete() { return Delete },
    Edit() { return Edit }
  },
  setup() {
    // 基础数据
    const userInfoStore = useUserInfoStore();
    const currentId = ref('');
    const paymentPageListDate = ref([]);
    const pageNum = ref(1);
    const pageSize = ref(5);
    const total = ref(0);
    const loading = ref(false);
    // 核心数据指标
    const totalAmount = ref(0);
    const totalOrder = ref(0);
    const totalRefund = ref(0); // 退款率(%)
    const orderGrowthRate = ref(null); // 订单增长率(%)
    const refundGrowthRate = ref(null); // 退款率变化(%)
    const amountGrowthRate = ref(null); // 金额增长率(%)
    const comparePeriod = ref(''); // 对比周期文本
    const trendTitle = ref('交易趋势'); // 图表标题
    // 筛选条件
    const formData = ref({
      paymentType: '',
      status: '',
      refundTime: '',
      year: '',
      month: ''
    });
    // 年度/月度数据存储
    const yearData = ref([]); // 年度数据列表
    const monthData = ref([]); // 月度数据列表
    const paymentListDate = ref([]); // 全部支付数据
    // 订单分页列表处理
    const getPaymentPageList = () => {
      const params = {
        params: {
          pageNum: pageNum.value,
          pageSize: pageSize.value,
          merchantId: currentId.value,
          year: formData.value.year,
          month: formData.value.month
        }
      };
      console.log(params)
      paymentPageList(params).then(res => {
        paymentPageListDate.value = res.data.records || [];
        total.value = res.data.count || 0;
      });
    };
    // 格式化支付方式
    const formatPaymentType = (type) => {
      switch (type) {
        case 1: return '微信';
        case 2: return '支付宝';
        default: return '未知';
      }
    };
    // 格式化支付状态
    const formatstatus = (status) => {
      switch (status) {
        case 0: return '未支付';
        case 1: return '已支付';
        case 2: return '已退款';
        default: return '未知';
      }
    };
    // 获取状态标签类型
    const getStatusType = (status) => {
      switch (status) {
        case 0: return 'warning';
        case 1: return 'success';
        case 2: return 'danger';
        default: return 'info';
      }
    };
    // 金额样式处理
    const getAmountStyle = (amount) => {
      const num = parseFloat(amount);
      if (isNaN(num)) return {};
      if (num < 500) return { color: '#409EFF' };
      if (num <= 1000) return { color: '#67C23A' };
      return { color: '#E6A23C' };
    };
    // 分页事件
    const handleSizeChange = (val) => {
      pageSize.value = val;
      getPaymentPageList();
    };
    const handleCurrentChange = (val) => {
      pageNum.value = val;
      getPaymentPageList();
    };
    // 获取全部支付数据
    const getPaymentList = async () => {
      loading.value = true;
      try {
        const params = {
          params: {
            merchantId: currentId.value,
            year: formData.value.year,
            month: formData.value.month,
          }
        };
        const res = await paymentList(params);
        paymentListDate.value = res.data || [];
        processPaymentData();
        renderCharts();
      } catch (err) {
        console.error('获取支付数据失败', err);
        ElMessage.error('获取数据失败');
      } finally {
        loading.value = false;
      }
    };
    // 初始化
    onMounted(() => {
      currentId.value = userInfoStore.userInfo.id;
      getPaymentList();
      getPaymentPageList();
      getYearData();
      getMonthData();
      // 窗口 resize 时重绘图表
      window.addEventListener('resize', renderCharts);
      return () => {
        window.removeEventListener('resize', renderCharts);
        Object.values(charts).forEach(chart => chart?.destroy());
      };
    });
    // 监听支付数据变化，更新图表
    watch(paymentListDate, () => {
      processPaymentData();
      renderCharts();
    });
    // 获取年度
    const getYearData = async () => {
      const params = { params: { merchantId: currentId.value } };
      const res = await paymentYearList(params);
      yearData.value = res.data || [];
    };
    //月度数据
    const getMonthData = async () => {
      const params = { params: { merchantId: currentId.value } };
      const res = await paymentMonthList(params);
      monthData.value = res.data || [];
    };
    // 格式化增长率显示（处理无数据情况）
    // const formatRate = (rate) => {
    //   return rate === null ? '--' : rate.toFixed(1);
    // };
    const formatRate = (rate) => {
      if (rate === null || isNaN(rate) || !isFinite(rate)) {
        return '--'; // 无效值时显示--
      }
      return rate.toFixed(1);
    };
    // 核心逻辑：处理日期查询
    const handleDateQuery = async () => {
      // 先获取最新的年度/月度数据
      await getYearData();
      await getMonthData();
      // 更新分页列表
      getPaymentPageList();
      // 清空之前的指标
      amountGrowthRate.value = null;
      orderGrowthRate.value = null;
      refundGrowthRate.value = null;
      comparePeriod.value = '';
      if (formData.value.year) {
        // 仅查询年度数据
        handleYearQuery();
      }else {
        // 无有效查询条件
        ElMessage.warning('请至少输入年份');
        return;
      }
      //调用getPaymentList刷新当前筛选条件下的支付记录
      await getPaymentList();
      // 更新图表数据
      processPaymentData();
      renderCharts();

    };
    // 处理年度查询
    const handleYearQuery = () => {
      const targetYear = Number(formData.value.year);
      console.log("年度查询"+targetYear)
      console.log(yearData.value)

      console.log("手动遍历验证:");
      let foundCurrent = false;
      let foundPrev = false;

      yearData.value.forEach(item => {
        const yearNum = Number(item.year);
        if (yearNum === targetYear) foundCurrent = true;
        if (yearNum === (targetYear - 1)) foundPrev = true;
      });

      console.log(`目标年份(${targetYear})是否存在:`, foundCurrent);
      console.log(`前一年份(${targetYear-1})是否存在:`, foundPrev);
      // 当前年数据
      const current = yearData.value.find(item => Number(item.year) === targetYear);
      // console.log('目标年份数据'+current.totalOrder)
      // 上一年数据
      const prev = yearData.value.find(item => Number(item.year) === targetYear - 1);
      // console.log('上一年分数据'+prev)
      if (!current) {
        ElMessage.warning(`未找到${targetYear}年的数据`);
        return;
      }
      // 基础数据赋值（转换为数字）
      totalAmount.value = Number(current.totalAmount);
      totalOrder.value = Number(current.totalOrder);
      console.log("基础数据赋值"+ {totalAmount}+";"+totalOrder.value)


      // 计算退款率：(退款次数/总订单数)*100
      totalRefund.value = current.totalOrder > 0
          ? (Number(current.totalRefundTime) / Number(current.totalOrder) * 100).toFixed(1)
          : 0;


      // console.log("计算退款率"+(Number(current.totalRefundTime) / Number(current.totalOrder) * 100).toFixed(1))
      console.log("计算退款率"+totalRefund.value)
      // 计算增长率（与上一年对比）
      if (prev) {
        comparePeriod.value = `${targetYear - 1}年`;
        // 金额增长率
        amountGrowthRate.value = formatRate(prev.totalAmount > 0
            ? ((current.totalAmount - prev.totalAmount) / prev.totalAmount * 100)
            : (current.totalAmount > 0 ? 100 : 0));
        console.log("金额增长率"+amountGrowthRate.value)
        // 订单增长率
        orderGrowthRate.value = formatRate(prev.totalOrder > 0
            ? ((current.totalOrder - prev.totalOrder) / prev.totalOrder * 100)
            : (current.totalOrder > 0 ? 100 : 0));
        console.log("订单增长率"+orderGrowthRate.value)
        // 退款率变化（当前退款率 - 上一年退款率）
        const currentRefundRate = current.totalOrder > 0 ? (current.totalRefundTime / current.totalOrder * 100) : 0;
        const prevRefundRate = prev.totalOrder > 0 ? (prev.totalRefundTime / prev.totalOrder * 100) : 0;
        refundGrowthRate.value = formatRate(currentRefundRate - prevRefundRate);
        console.log("退款率变化"+refundGrowthRate.value)
      } else {
        comparePeriod.value = '无历史数据';
      }
      // 设置图表标题
      trendTitle.value = `${targetYear}年各月交易趋势`;
    };
    // 重置查询条件
    const resetDateFilter = () => {
      formData.value.year = '';
      getPaymentList();
      // 重置指标
      amountGrowthRate.value = null;
      orderGrowthRate.value = null;
      refundGrowthRate.value = null;
      comparePeriod.value = '';
      trendTitle.value = '交易趋势';
      // 重置数据
      totalAmount.value = 0;
      totalOrder.value = 0;
      totalRefund.value = 0;
      formData.value.year = '';
      // 重置图表
      processPaymentData();
      renderCharts();
      // 重置分页列表
      getPaymentPageList();
    };
    // 图表数据处理
    const chartData = ref({
      paymentMethod: { labels: ['微信支付', '支付宝'], data: [0, 0] },
      paymentStatus: { labels: ['未支付', '已支付', '已退款'], data: [0, 0, 0] },
      dailyTrend: { labels: [], data: [] },
      amountDistribution: { labels: ['<100', '100-200', '200-500', '500-1000', '>1000'], data: [0, 0, 0, 0, 0] }
      // 【删除部分1】移除退款时间分析的图表数据定义
      // refundTime: { labels: Array.from({ length: 12 }, (_, i) => `${i*2}:00`), data: new Array(12).fill(0) }
    });
    // 处理支付数据生成图表所需数据（核心修改部分）
    const processPaymentData = () => {
      // 重置图表数据
      chartData.value = {
        paymentMethod: { labels: ['微信支付', '支付宝'], data: [0, 0] },
        paymentStatus: { labels: ['未支付', '已支付', '已退款'], data: [0, 0, 0] },
        dailyTrend: { labels: [], data: [] },
        amountDistribution: { labels: ['<100', '100-200', '200-500', '500-1000', '>1000'], data: [0, 0, 0, 0, 0] }
        // 【删除部分2】移除退款时间分析的图表数据重置
        // refundTime: { labels: Array.from({ length: 12 }, (_, i) => `${i*2}:00`), data: new Array(12).fill(0) }
      };
      if (formData.value.year && !formData.value.month) {
        // 仅查询年度数据：该年的月度分布
        const targetYear = Number(formData.value.year);
        const monthlyDataOfYear = monthData.value
            .filter(item => Number(item.year) === targetYear)
            .sort((a, b) => Number(a.month) - Number(b.month));
        chartData.value.dailyTrend.labels = monthlyDataOfYear.map(item => `${item.month}月`);
        chartData.value.dailyTrend.data = monthlyDataOfYear.map(item => Number(item.totalAmount));
        trendTitle.value = `${targetYear}年各月交易趋势`;
      } else if (formData.value.year && formData.value.month) {
        // 查询月度数据：该月的日期分布
        const daysInMonth = new Date(formData.value.year, formData.value.month, 0).getDate();
        chartData.value.dailyTrend.labels = Array.from({ length: daysInMonth }, (_, i) => `${i+1}日`);
        // 实际项目中应替换为接口返回的每日数据
        chartData.value.dailyTrend.data = Array.from({ length: daysInMonth }, () =>
            Math.floor(Math.random() * 100) + 10
        );
        trendTitle.value = `${formData.value.year}年${formData.value.month}月每日交易趋势`;
      } else {
        // 【核心修改】年月都未输入：按年份绘制各年的交易数据对比
        // 1. 获取所有年份并排序（从旧到新）
        const allYears = [...new Set(yearData.value.map(item => Number(item.year)))]
            .sort((a, b) => a - b);

        if (allYears.length === 0) {
          // 无数据时显示提示
          chartData.value.dailyTrend.labels = ['无数据'];
          chartData.value.dailyTrend.data = [0];
          trendTitle.value = '各年交易趋势对比（无数据）';
          return;
        }
        // 2. 按年份整理数据（总交易额）
        chartData.value.dailyTrend.labels = allYears.map(year => `${year}年`);
        chartData.value.dailyTrend.data = allYears.map(year => {
          const yearItem = yearData.value.find(item => Number(item.year) === year);
          return yearItem ? Number(yearItem.totalAmount) : 0;
        });
        // 3. 更新图表标题
        trendTitle.value = `各年交易总额趋势对比`;
      }
      // 处理其他图表（支付方式、状态等，保持原有逻辑）
      let paymentTypeCount = { 1: 0, 2: 0 };
      let statusCount = { 0: 0, 1: 0, 2: 0 };
      let amountRangeCount = [0, 0, 0, 0, 0];

      paymentListDate.value.forEach(payment => {
        // 支付方式统计
        if (payment.paymentType) {
          paymentTypeCount[payment.paymentType]++;
        }
        // 支付状态统计
        if (payment.status !== undefined) {
          statusCount[payment.status]++;
        }
        // 金额分布统计
        const amt = Number(payment.amount || 0);
        if (amt < 100) amountRangeCount[0]++;
        else if (amt < 200) amountRangeCount[1]++;
        else if (amt < 500) amountRangeCount[2]++;
        else if (amt < 1000) amountRangeCount[3]++;
        else amountRangeCount[4]++;
        // 【删除部分3】移除退款时间相关的数据统计逻辑（如果有）
      });

      chartData.value.paymentMethod.data = [paymentTypeCount[1], paymentTypeCount[2]];
      chartData.value.paymentStatus.data = [statusCount[0], statusCount[1], statusCount[2]];
      chartData.value.amountDistribution.data = amountRangeCount;
    };

    // 渲染图表
    let charts = {};
    const renderCharts = () => {
      // 销毁已有图表
      Object.values(charts).forEach(chart => chart?.destroy());

      // 1. 支付方式分布
      const paymentMethodCtx = document.getElementById('paymentMethodChart').getContext('2d');
      charts.paymentMethod = new Chart(paymentMethodCtx, {
        type: 'doughnut',
        data: {
          labels: chartData.value.paymentMethod.labels,
          datasets: [{
            data: chartData.value.paymentMethod.data,
            backgroundColor: ['#4CAF50', '#2196F3'],
            borderWidth: 0
          }]
        },
        options: {
          responsive: true,
          maintainAspectRatio: false,
          plugins: { legend: { position: 'bottom' } }
        }
      });

      // 2. 支付状态统计
      const paymentStatusCtx = document.getElementById('paymentStatusChart').getContext('2d');
      charts.paymentStatus = new Chart(paymentStatusCtx, {
        type: 'bar',
        data: {
          labels: chartData.value.paymentStatus.labels,
          datasets: [{
            label: '订单数量',
            data: chartData.value.paymentStatus.data,
            backgroundColor: ['#FFC107', '#4CAF50', '#F44336'],
            borderRadius: 4
          }]
        },
        options: {
          responsive: true,
          maintainAspectRatio: false,
          scales: { y: { beginAtZero: true } }
        }
      });

      // 3. 交易趋势
      const transactionTrendCtx = document.getElementById('transactionTrendChart').getContext('2d');
      charts.transactionTrend = new Chart(transactionTrendCtx, {
        type: 'line',
        data: {
          labels: chartData.value.dailyTrend.labels,
          datasets: [{
            label: '交易金额',
            data: chartData.value.dailyTrend.data,
            borderColor: '#2196F3',
            backgroundColor: 'rgba(33, 150, 243, 0.1)',
            fill: true,
            tension: 0.4
          }]
        },
        options: {
          responsive: true,
          maintainAspectRatio: false,
          scales: {
            y: {
              beginAtZero: true,
              ticks: { callback: (v) => `¥${v.toLocaleString()}` }
            }
          }
        }
      });
      // 4. 金额分布
      const amountDistributionCtx = document.getElementById('amountDistributionChart').getContext('2d');
      charts.amountDistribution = new Chart(amountDistributionCtx, {
        type: 'bar',
        data: {
          labels: chartData.value.amountDistribution.labels,
          datasets: [{
            label: '订单数量',
            data: chartData.value.amountDistribution.data,
            backgroundColor: ['rgba(255,99,132,0.7)', 'rgba(54,162,235,0.7)', 'rgba(255,206,86,0.7)', 'rgba(75,192,192,0.7)', 'rgba(153,102,255,0.7)'],
            borderRadius: 4
          }]
        },
        options: {
          responsive: true,
          maintainAspectRatio: false,
          scales: { y: { beginAtZero: true } }
        }
      });

      // 【删除部分4】移除退款时间分析图表的渲染代码
      // // 5. 退款时间分析
      // const refundTimeCtx = document.getElementById('refundTimeChart').getContext('2d');
      // charts.refundTime = new Chart(refundTimeCtx, {
      //   type: 'bar',
      //   data: {
      //     labels: chartData.value.refundTime.labels,
      //     datasets: [{
      //       label: '退款次数',
      //       data: chartData.value.refundTime.data,
      //       backgroundColor: 'rgba(244, 67, 54, 0.6)',
      //       borderRadius: 4
      //     }]
      //   },
      //   options: {
      //     responsive: true,
      //     maintainAspectRatio: false,
      //     scales: { y: { beginAtZero: true } }
      //   }
      // });
    };
    // 金额格式化过滤器
    const currency = (value) => {
      if (!value) return '¥0.00';
      return '¥' + Number(value).toFixed(2).replace(/\d(?=(\d{3})+\.)/g, '$&,');
    };
    return {
      paymentPageListDate,
      pageNum,
      pageSize,
      total,
      handleSizeChange,
      handleCurrentChange,
      formatPaymentType,
      formatstatus,
      getStatusType,
      getAmountStyle,
      formData,
      handleDateQuery,
      resetDateFilter,
      totalAmount,
      totalOrder,
      totalRefund,
      orderGrowthRate,
      refundGrowthRate,
      amountGrowthRate,
      comparePeriod,
      trendTitle,
      formatRate,
      currency,
      paymentListDate,
      loading
    };
  }
};
</script>

<style scoped>
.page-container {
  margin-bottom: 20px;
}

.card-grid {
  display: flex;
  gap: 20px;
  width: 100%;
}

.data-card {
  flex: 1;
  background: white;
  border-radius: 8px;
  padding: 20px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  border-left: 4px solid;
}

.data-card:nth-child(1) { border-color: #2196F3; }
.data-card:nth-child(2) { border-color: #4CAF50; }
.data-card:nth-child(3) { border-color: #F44336; }

.chart-container {
  padding: 20px;
}

.chart-row {
  display: flex;
  gap: 20px;
  width: 100%;
}

.chart-item {
  flex: 1;
  display: flex;
  flex-direction: column;
  height: 100%;
}

.chart-wrapper {
  flex: 1;
  display: flex;
  align-items: flex-end;
  min-height: 300px;
}

.date-filter {
  display: flex;
  align-items: center;
}

@media (max-width: 768px) {
  .card-grid, .chart-row {
    flex-direction: column;
  }
  .chart-wrapper {
    min-height: 200px;
  }
  .date-filter {
    flex-direction: column;
    align-items: flex-start;
  }
  .date-filter .el-input {
    width: 100% !important;
    margin-bottom: 10px;
    margin-right: 0 !important;
  }
}
</style>